﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Collections.Generic;
namespace SecurityLib
{
	public static class Security
	{
		static Security()
		{
			UserRoles = new List<string>();
		}
		public static readonly DependencyProperty AuthenticatedRolesProperty = 
            DependencyProperty.RegisterAttached("AuthenticatedRoles", typeof(string), typeof(Security),
			new PropertyMetadata("", AssertRoles));

		public static void SetAuthenticatedRoles(UIElement element, string value)
		{
			element.SetValue(AuthenticatedRolesProperty, value);
		}
		public static string GetAuthenticatedRoles(UIElement element)
		{
			return (string)element.GetValue(AuthenticatedRolesProperty);
		}

		public static List<string> UserRoles { get; set; }

        /// <summary>
        /// Set the visibility of the UI element based on whether the user has the apropriate priveleges.
        /// </summary>
        /// <param name="sender">The UI element to change the visibility of</param>
        /// <param name="e">The property changed arguments</param>
		static void AssertRoles(DependencyObject sender, DependencyPropertyChangedEventArgs e)
		{
			string Value = (string)e.NewValue;
			if (ProcessFullString(Value))
			{
				//User is Authenticated
				((UIElement)sender).Visibility = Visibility.Visible;
			}
			else
			{
				//User is not Authenticated
				((UIElement)sender).Visibility = Visibility.Collapsed;
			}
		}

		static bool ProcessFullString(string Value)
		{
			if (Value == "")
			{
				return true;
			}
			string[] Ands;
			if (Value.Contains("."))
			{
				Ands = Value.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
			}
			else
			{
				Ands = new string[] { Value };
			}
			return Ands.All(ProcessOrString);
		}
		static bool ProcessOrString(string Value)
		{
			string[] Ors;
			if (Value.Contains("+"))
			{
				Ors = Value.Split(new string[] { "+" }, StringSplitOptions.RemoveEmptyEntries);
			}
			else
			{
				Ors = new string[] { Value };
			}
			return Ors.Any(IsUserInRole);
		}
		static bool IsUserInRole(string Role)
		{
			if (Role.ToLower()=="true")
			{
				return true;
			}
			else if (Role.ToLower()=="false")
			{
				return false;
			}
			return UserRoles.Contains(Role);
		}
	}
}
